home *** CD-ROM | disk | FTP | other *** search
- Path: rain.fr!world-net!usenet
- From: Frederic LACHASSE <lachass@worldnet.fr>
- Newsgroups: comp.lang.c++
- Subject: Re: Specifying Data Layout
- Date: Sun, 17 Mar 1996 07:35:15 +0000
- Organization: World-Net information exchange, Internet provider.
- Message-ID: <VA.0000006c.00028969@fred>
- References: <1996Mar14.173643.8651@nosc.mil>
- Reply-To: lachass@worldnet.fr
- NNTP-Posting-Host: client122.sct.fr
- X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
-
- In article <1996Mar14.173643.8651@nosc.mil>, sampson@cod.nosc.mil (Charles H.
- Sampson) wrote:
- >
- > I've just finished reading the reference manual part of Stroustrup's
- > "The C++ Programming Language" (2nd ed) and have a number of questions.
- > This one is particularly important to a project I'm working on. A quick
- > search of the FAQ didn't turn up anything, nor does it seem to appear in
- > the 1400+ articles currently in the comp.lang.c++ newsgroup on my news
- > server.
- >
- > Is there some way of precisely specifying the memory layout of a
- > struct? In other words, can you say, "This struct is to occupy 3 words of
- > memory, element foo is to occupy bits 5-12 of word 1, element fern is to
- > occupy ..."? If it can be done with a struct, can it also be done with a
- > class (specifying locations for the data members only)? In this case, can
- > you also control the gizmo that is used to distinguish the various values
- > of a class hierarchy, both where it is to be allocated and the values to be
- > used to identify specific members of the hierarchy?
- >
- The way to do it is:
-
- struct Packed
- {
- unsigned short a:3; // 3 bits
- unsigned short b:5; // 5 more bits
- unsigned short c:8; // the remaining 8 bits for a 16 bits unsigned short
- };
-
- The a, b, c member of the Packed struct will be stored in 2 bytes of memory.
-
- BTW, the same syntax works for classes.
-
- The exact layout of the bits is implementation dependant as:
- - unsigned short isn't necessarily 16 bits long,
- - the processor store most significant bytes first or last.
- So read compiler documentation and experiment to find out which exact layout
- will work for you.
-
- One reason you've found nothing in the C++ FAQ is that it is a C syntax that
- C++ have inherited. As most C++ programmers learn C first, they already know
- this trick.
-
- Frederic LACHASSE (ECP 86)
- CompuServe: 100530,2005
- Internet: lachass@worldnet.fr
-
-